﻿package little.bunny;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MyAddress extends Activity{
	private Button btn_save;
	private EditText txtInputProv;
	private EditText txtInputCity;
	private EditText txtInputAddr;
	private EditText txtInputTel;
	private Button backButton;
	private Spinner spinner_area;
	private String s_area;
	
	private static final String[] m_area={"罗湖区","福田区","南山区","宝安区","龙华新区","光明新区","龙岗区"};
	
	private final String serviceNameSpace = "http://littlebunny.com/";
	private final String serviceUrl = "http://www.littlebunny.com.cn/bunny_service/bunny_service.asmx";
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_addr);
				
		s_area = "";
		
		txtInputProv = (EditText) findViewById(R.id.editprov);
		txtInputCity = (EditText) findViewById(R.id.editcity);
		txtInputAddr = (EditText) findViewById(R.id.editaddr);
		txtInputTel = (EditText) findViewById(R.id.edittel);
		
		addItemsOnSpinnerArea();
		
		get_user_data();
		
		btn_save = (Button) findViewById(R.id.btn_save);
		
		btn_save.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				user_update();
			}
		});
				
		backButton = (Button) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	private void user_update() 
	{
		//if (txtInputArea.getText().toString().length() == 0) {
		//	ShowMsg("请输入地区.");
		//	return;
		//}

		if (txtInputAddr.getText().toString().length() == 0) {
			ShowMsg("请输入地址.");
			return;
		}
		
		if (NetFunction.CheckNetStatus(this)==false)
		{
			ShowMsg("没有找到有效的网络.");
			return;
		}
		
		//Toast.makeText(this, "检查用户注册信息...", Toast.LENGTH_LONG).show();
		
		final ProgressDialog pDialog = ProgressDialog.show(this, "请稍等",
				"更新用户信息...", true);
		
		pDialog.setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_BACK){
					pDialog.dismiss();
				}
				return false;
			}
		});
		
		Thread networkThread2 = new Thread() {
			@Override
			public void run() {
				String user_code;
				String user_pass;
				SharedPreferences sharedata2 = getSharedPreferences("user_data", 0);  
				user_code = sharedata2.getString("name", null);
				user_pass = sharedata2.getString("pass_key", null);
				
				String method_name = "CustomUpdate";
				String SOAP_ACTION = "http://littlebunny.com/CustomUpdate";
				
				SoapObject request = new SoapObject(serviceNameSpace, method_name);
				request.addProperty("user_id", user_code);
				request.addProperty("u_pass", user_pass);
				
				String s1="A1||" + txtInputProv.getText().toString() + "|:|";
				String s2="A2||" + txtInputCity.getText().toString() + "|:|";
				String s3="A3||" + s_area + "|:|";
				String s4="A4||" + txtInputAddr.getText().toString() + "|:|";
				String s5="A5||" + txtInputTel.getText().toString() + "|:|";
				
				request.addProperty("u_data", s1 + s2 + s3 + s4 + s5);

				SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope2.dotNet = true;
				envelope2.setOutputSoapObject(request);
				
				try {
					HttpTransportSE ht = new HttpTransportSE(serviceUrl);
					ht.call(SOAP_ACTION, envelope2);

					SoapPrimitive response = (SoapPrimitive) envelope2.getResponse();
					final String result2 = response.toString();
					
					pDialog.dismiss();// 隐藏进度条
					
					runOnUiThread(new Runnable() {
						public void run() {
							//ShowMsg(result2);
							//更新失败
							if (result2.startsWith("99:", 0))
							{
								new AlertDialog.Builder(MyAddress.this)
								.setTitle("更新用户资料")
								.setMessage(result2.substring(3))
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {
											}
										}).show();
							}
							else
							{
								//更新成功，转向主页
								Intent myIntent=new Intent(MyAddress.this,MyHome.class);
								startActivity(myIntent);
								/*
								new AlertDialog.Builder(MyAddress.this)
								.setTitle("更新用户资料")
								.setMessage("更新成功")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {
												
												Intent myIntent=new Intent();
												myIntent.setClass(MyAddress.this, MyHome.class);
												
												startActivity(myIntent);
											}
										}).show();
								*/
							}
						}
					});
				} catch (Exception e) {
					pDialog.dismiss();
					e.printStackTrace();
					
					ShowMyDialog("网络信号异常","请查看网络连接，稍后再试...");
				}
			}
		};

		networkThread2.start();
	}
	
	private void get_user_data() 
	{
		if (NetFunction.CheckNetStatus(this)==false)
		{
			ShowMsg("没有找到有效的网络.");
			return;
		}
		
		Thread networkThread1 = new Thread() {
			@Override
			public void run() {
				String user_code;
				String user_pass;
				SharedPreferences sharedata2 = getSharedPreferences("user_data", 0);  
				user_code = sharedata2.getString("name", null);
				user_pass = sharedata2.getString("pass_key", null);
				
				String method_name = "GetCustomData";
				String SOAP_ACTION = "http://littlebunny.com/GetCustomData";
				
				SoapObject request = new SoapObject(serviceNameSpace, method_name);
				request.addProperty("user_id", user_code);
				request.addProperty("u_pass", user_pass);
				
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				
				try {
					HttpTransportSE ht = new HttpTransportSE(serviceUrl);
					ht.call(SOAP_ACTION, envelope);

					SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
					final String result1 = response.toString();
					
					//Toast.makeText(this, "读取完毕.", Toast.LENGTH_LONG).show();
					
					runOnUiThread(new Runnable() {
						public void run() {
							//读取失败
							if (result1.startsWith("99:", 0))
							{
								new AlertDialog.Builder(MyAddress.this)
								.setTitle("读取用户资料")
								.setMessage(result1.substring(3))
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {
											}
										}).show();
							}
							else
							{
								//读取成功
								show_user_data(result1);
							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					
					ShowMyDialog("网络信号异常","请查看网络连接，稍后再试...");
				}
			}
		};

		networkThread1.start();
	}
	
	private void show_user_data(String result_data) {  
    	String[] temp = null; 
    	//Toast.makeText(this, result_data, Toast.LENGTH_LONG).show();
    	
    	if ((result_data.indexOf("|")==-1))
    	{
    		return;
    	}
    	
    	try
    	{
    		temp = result_data.split("\\|");  
        	if (temp.length>0)
        	{
	    		txtInputProv.setText(temp[0]);
	    		txtInputCity.setText(temp[1]);
	    		if (temp[2].length()>0)
	    		{
		    		for (int i=0;i<m_area.length-1;i++)
		    		{
		    			if (m_area[i].equals(temp[2]))
		    			{
		    				spinner_area.setSelection(i);
		    				break;
		    			}
		    		}
	    		}
	    		
	    		txtInputAddr.setText(temp[3]);
	    		txtInputTel.setText(temp[4]);
        	}
    	}
    	catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	private void ShowMsg(String msg)
	{
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}
	
	private void ShowMyDialog(String title, String info)
	{
		new AlertDialog.Builder(MyAddress.this)
		.setTitle(title)
		.setMessage(info)
		.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						//MyLogin.this.finish();
					}
				}).show();
	}
	
	private void addItemsOnSpinnerArea()
	{
		ArrayAdapter<String> dataAdapter;
		spinner_area = (Spinner) findViewById(R.id.spinner_area);
		
		//将可选内容与ArrayAdapter连接起来  
		dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m_area);  
          
        //设置下拉列表的风格  
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
          
        //将adapter 添加到spinner中  
        spinner_area.setAdapter(dataAdapter);  
          
        //添加事件Spinner事件监听    
        spinner_area.setOnItemSelectedListener(new SpinnerListener());  
          
        //设置默认值  
        spinner_area.setVisibility(View.VISIBLE);  
	}
	
	//使用数组形式操作  
    public class SpinnerListener implements OnItemSelectedListener{  
  
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  
                long arg3) { 
        	s_area = m_area[arg2];
            //view.setText("你的血型是："+m_area[arg2]);  
        }  
  
        public void onNothingSelected(AdapterView<?> arg0) {  
        }  
    }  
}
